//
//  CGCommonSelectedView.m
//  仿京东地址选择器
//
//  Created by up72_2017_new on 2018/6/22.
//  Copyright © 2018年 up72_2017_new. All rights reserved.
//

#import "CGCommonSelectedView.h"

// RGB颜色转换（16进制->10进制）
#define kColorWithRGB(rgbValue) \
[UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16)) / 255.0 \
green:((float)((rgbValue & 0xFF00) >> 8)) / 255.0 \
blue:((float)(rgbValue & 0xFF)) / 255.0 alpha:1.0]

//设备物理尺寸
#define screen_width [UIScreen mainScreen].bounds.size.width
#define screen_height [UIScreen mainScreen].bounds.size.height

@interface CGCommonSelectedView ()<UIScrollViewDelegate,UIGestureRecognizerDelegate,UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UIScrollView *titleScrollView;   // 标题ScrollView
@property(nonatomic,strong)UIScrollView *contentScrollView; // 内容ScrollView
@property(nonatomic,strong)UIButton *radioBtn;              // 当前选中按钮
@property(nonatomic,strong)NSMutableArray *titleBtns;       // 标题按钮数组
@property(nonatomic,strong)UILabel *signLineView;           // 标记选中标题的线条
@property(nonatomic,strong)NSMutableArray *titleMarr;       // 选中的title标题数组
@property(nonatomic,strong)NSMutableArray *titleDataMarr;   // 选中title的Model数组
@property(nonatomic,assign)BOOL isclick;                    //判断是滚动还是点击
@property(nonatomic,strong)UIView *addAddressView;          // 控件根视图
@property(nonatomic,strong)NSMutableArray *tableViewMarr;   // 内容tableview数组
@property(nonatomic,strong)NSMutableArray *dataArr;         // 数据源
@end

@implementation CGCommonSelectedView
-(NSMutableArray *)titleBtns
{
    if (_titleBtns == nil) {
        _titleBtns = [[NSMutableArray alloc]init];
    }
    return _titleBtns;
}
-(NSMutableArray *)titleDataMarr
{
    if (_titleDataMarr == nil) {
        _titleDataMarr = [[NSMutableArray alloc]init];
    }
    return _titleDataMarr;
}

-(NSMutableArray *)titleMarr
{
    if (_titleMarr == nil) {
        _titleMarr = [[NSMutableArray alloc]init];
    }
    return _titleMarr;
}

-(NSMutableArray *)tableViewMarr
{
    if (_tableViewMarr == nil) {
        _tableViewMarr = [[NSMutableArray alloc]init];
    }
    return _tableViewMarr;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray arrayWithCapacity:1];
    }
    return _dataArr;
}

/**
 初始化选择控件

 @return 控件对象
 */
- (CGCommonSelectedView *)initSelectedWidgetView {
    
    // 初始化设置
    if (!_titleNormalColor) _titleNormalColor = kColorWithRGB(0x333333);
    if (!_titleSelectedColor) _titleSelectedColor = kColorWithRGB(0x09c04e);
    if (!_bigTitleColor) _bigTitleColor = kColorWithRGB(0x333333);
    if (!_bigTitlefont) _bigTitlefont = [UIFont systemFontOfSize:17];
    if (!_titlefont) _titlefont = [UIFont systemFontOfSize:13];
    if (!_signLineViewColor) _signLineViewColor = kColorWithRGB(0x09c04e);
    if (_defaultHeight < 5) _defaultHeight = 350;
    if (_titleScrollViewH < 5) _titleScrollViewH = 37;
    
    self.frame = CGRectMake(0, 0, screen_width, screen_height);
    self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
    self.hidden = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hidden)];
    tap.delegate = self;
    [self addGestureRecognizer:tap];
    //设置添加地址的View
    self.addAddressView = [[UIView alloc]init];
    self.addAddressView.frame = CGRectMake(0, screen_height, screen_width, _defaultHeight);
    self.addAddressView.backgroundColor = [UIColor whiteColor];  // 选择控件的背景色
    [self addSubview:self.addAddressView];
    UILabel * titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(40, 10, screen_width - 80, 30)];
    titleLabel.text = _title;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = _bigTitleColor;
    titleLabel.font = _bigTitlefont;
    [self.addAddressView addSubview:titleLabel];
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    cancelBtn.frame =CGRectMake(CGRectGetMaxX(self.addAddressView.frame) - 40, 10, 30, 30);
    cancelBtn.tag = 1;
    [cancelBtn setImage:[UIImage imageNamed:@"close_pay"] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(hidden) forControlEvents:UIControlEventTouchUpInside];
    [self.addAddressView addSubview:cancelBtn];
    
    [self setupTitleScrollView];    // 初始化标题
    [self setupContentScrollView];  // 初始化列表
    return self;
}

-(void)setupTitleScrollView{
    //TitleScrollView和分割线
    self.titleScrollView = [[UIScrollView alloc] init];
    self.titleScrollView.showsHorizontalScrollIndicator = NO;
    self.titleScrollView.frame = CGRectMake(0, 50, screen_width, _titleScrollViewH);
    [self.addAddressView addSubview:self.titleScrollView];
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.titleScrollView.frame), screen_width, 0.5)];
    lineView.backgroundColor = kColorWithRGB(0xe5e5e5);
    [self.addAddressView addSubview:(lineView)];
    
    _signLineView = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];
    _signLineView.tag = 101;   // 标记不被移除
    _signLineView.backgroundColor = _signLineViewColor;   // 选中Line
    [self.titleScrollView addSubview:(_signLineView)];
}

-(void)setupContentScrollView{
    //ContentScrollView
    CGFloat y  =  CGRectGetMaxY(self.titleScrollView.frame) + 1;
    self.contentScrollView = [[UIScrollView alloc] init];
    self.contentScrollView.showsHorizontalScrollIndicator = NO;
    self.contentScrollView.frame = CGRectMake(0, y, screen_width, self.defaultHeight - y);
    [self.addAddressView addSubview:self.contentScrollView];
    self.contentScrollView.delegate = self;
    self.contentScrollView.pagingEnabled = YES;
//    self.contentScrollView.bounces = NO;
}

#pragma mark - 显示
-(void)show {
    self.hidden = NO;
    [UIView animateWithDuration:0.2 animations:^{
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
        self.addAddressView.frame = CGRectMake(0, screen_height - self.defaultHeight, screen_width, self.defaultHeight);
    }];
}

#pragma mark - 隐藏
- (void)hidden {
    [UIView animateWithDuration:0.2 animations:^{
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.1];
        self.addAddressView.frame = CGRectMake(0, screen_height, screen_width, 200);
    } completion:^(BOOL finished) {
        self.hidden = YES;
    }];
}





/**
 添加一个数据源
 
 @param model 数据源模型
 */
- (void)addDataWithModel:(CGRootModel *)model {
    if (model) {
        [self.dataArr addObject:model];
        [self setupAllTitle:self.dataArr.count - 1];
    } else {
        [self setupAllTitle:self.dataArr.count - 1];
        if (self.selectedFinishBlock) {
            self.selectedFinishBlock(self.titleDataMarr);
        }
        [self hidden];
    }
}


/**
 更新标题
 
 @param selectId 选中id
 */
-(void)setupAllTitle:(NSInteger)selectId{
    for (UIView * view in [self.titleScrollView subviews]) {
        if (view.tag != 101) {
            [view removeFromSuperview];
        }
    }
    [self.titleBtns removeAllObjects];
    CGFloat btnH = self.titleScrollViewH;
    
    
    if (self.titleMarr.count <= selectId) { // 没有添加过
        if (selectId >= self.tableViewMarr.count) {
            UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, screen_width, 200) style:UITableViewStylePlain];
            tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
            [tableView registerNib:[UINib nibWithNibName:@"CustomAddressCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"CustomAddressCellStr"];
            tableView.estimatedRowHeight = 100;  //  随便设个不那么离谱的值
            tableView.rowHeight = UITableViewAutomaticDimension;
            tableView.delegate = self;
            tableView.dataSource = self;
            tableView.tag = selectId;
            [self.tableViewMarr addObject:tableView];
        }
        [self.titleMarr addObject:@"请选择"];
    }
    
    CGFloat x = 10;
    CGFloat lastBtnWidth = 0;
    for (int i = 0; i < self.titleMarr.count ; i++) {
        NSString   *title = self.titleMarr[i];
        
        NSDictionary *attributes = @{NSFontAttributeName:_titlefont};
        CGFloat titlelenth = [title boundingRectWithSize:CGSizeMake(2000, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
        
        if (_titleMaxWidth > 0 && titlelenth > _titleMaxWidth) {    // 限制标题最大长度
            titlelenth = _titleMaxWidth;
        }
        lastBtnWidth = titlelenth;
        UIButton *titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [titleBtn setTitle:title forState:UIControlStateNormal];
        titleBtn.tag = i;
        [titleBtn setTitleColor:_titleNormalColor forState:UIControlStateNormal];
        [titleBtn setTitleColor:_titleSelectedColor forState:UIControlStateSelected];
        titleBtn.selected = NO;
        titleBtn.frame = CGRectMake(x, 0, titlelenth, btnH);
        x  = titlelenth + 10 + x;
        [titleBtn.titleLabel setFont:_titlefont];
        [titleBtn addTarget:self action:@selector(titleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.titleBtns addObject:titleBtn];
        if (i == selectId) {
            [self titleBtnClick:titleBtn];
        }
        [self.titleScrollView addSubview:(titleBtn)];
    }
    self.titleScrollView.contentSize =CGSizeMake(x, 0);
    self.contentScrollView.contentSize = CGSizeMake(self.titleMarr.count * screen_width, 0);
}

#pragma mark - 点击标题按钮
-(void)titleBtnClick:(UIButton *)titleBtn{
    
    self.radioBtn.selected = NO;
    titleBtn.selected = YES;
    [self setupOneTableView:titleBtn.tag];
    CGFloat x  = titleBtn.tag * screen_width;
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.contentScrollView.contentOffset = CGPointMake(x, 0);
        weakSelf.signLineView.frame = CGRectMake(CGRectGetMinX(titleBtn.frame), self.titleScrollViewH - 3,titleBtn.frame.size.width, 3);
    }];
    self.radioBtn = titleBtn;
    self.isclick = YES;
    
    // 处理选中标题的显示问题
    if (CGRectGetMaxX(titleBtn.frame) > screen_width) {
        if (self.titleScrollView.contentSize.width - CGRectGetMinX(titleBtn.frame) > 0 && self.titleScrollView.contentSize.width - CGRectGetMinX(titleBtn.frame) < screen_width) {
            self.titleScrollView.contentOffset = CGPointMake(self.titleScrollView.contentSize.width - screen_width,0);
        } else {
            // 右边超出屏幕
            self.titleScrollView.contentOffset = CGPointMake(CGRectGetMinX(titleBtn.frame) - 10, 0);
        }
    } else {
        self.titleScrollView.contentOffset = CGPointMake(0, 0);
    }
}

#pragma mark - 初始化一个新的TableView列表
-(void)setupOneTableView:(NSInteger)btnTag{
    UITableView  * contentView= self.tableViewMarr[btnTag];
    [contentView reloadData];
    if (contentView.superview != nil) {
        return;
    }
    CGFloat  x= btnTag * screen_width;
    contentView.frame = CGRectMake(x, 0, screen_width, self.contentScrollView.bounds.size.height);
    [self.contentScrollView addSubview:(contentView)];
}

#pragma mark - UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSInteger leftI  = scrollView.contentOffset.x / screen_width;
    if (scrollView.contentOffset.x / screen_width != leftI){
        self.isclick = NO;
    }
    if (self.isclick == NO) {
        if (scrollView.contentOffset.x / screen_width == leftI){
            UIButton * titleBtn  = self.titleBtns[leftI];
            [self titleBtnClick:titleBtn];
        }
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (tableView.tag <= self.dataArr.count) {
        CGRootModel *rootModel = self.dataArr[tableView.tag];
        return rootModel.itemArr.count;
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * AddressAdministerCellIdentifier = @"CustomAddressCellStr";
    CustomAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:AddressAdministerCellIdentifier];
    
    CGRootModel *rootModel = self.dataArr[tableView.tag];
    CGCommonItemModel *model = rootModel.itemArr[indexPath.row];
    cell.addressLabel.text = model.title;
    cell.model = model;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CGRootModel *currentRootModel = self.dataArr[tableView.tag];
    
    CGCommonItemModel *selectedModel = currentRootModel.itemArr[indexPath.row];
    
    BOOL isReplaceItemData = selectedModel.isSelected;
    
    // 判断是否选中
    if (!selectedModel.isSelected) {    // 未选中
        for (CGCommonItemModel *model in currentRootModel.itemArr) {
            model.isSelected = NO;
        }
        selectedModel.isSelected = YES;
        [tableView reloadData];
        
        // 如果下一级存在内容，那么清空选中状态
        while (self.titleDataMarr.count > tableView.tag) {
            [self.titleDataMarr removeLastObject];
        }
        while (self.titleMarr.count > tableView.tag + 1) {
            [self.titleMarr removeLastObject];
        }
        while (self.dataArr.count > tableView.tag + 1) {
            [self.dataArr removeLastObject];
        }
    }
    
    if (!currentRootModel.isEnd) {   // 不是最后一项
        [self.titleMarr replaceObjectAtIndex:tableView.tag withObject:selectedModel.title];  // 替换标题
        
        if (isReplaceItemData) { // 选中的只进行数据替换
            if (self.dataArr.count > tableView.tag + 1) {   // 不是最后一个列表,只进行替换
                [self setupAllTitle:tableView.tag + 1];
            } else {
                if (self.clickBlock) {
                    self.clickBlock(selectedModel, tableView.tag + 1);
                }
            }
        } else {    // 获取新的数据
            [self.titleDataMarr addObject:selectedModel]; // 添加选中的item
            
            if (self.clickBlock) {
                self.clickBlock(selectedModel, tableView.tag + 1);
            }
        }
    } else {    // 最后一项
        [self.titleMarr replaceObjectAtIndex:tableView.tag withObject:selectedModel.title];  // 替换标题
        [self.titleDataMarr addObject:selectedModel]; // 添加选中的item
        [self setupAllTitle:tableView.tag];
        
        if (self.selectedFinishBlock) {
            self.selectedFinishBlock(self.titleDataMarr);
        }
        [self hidden];
    }
}

//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return  40;
//}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([NSStringFromClass(touch.view.classForCoder) isEqualToString: @"UITableViewCellContentView"] || touch.view == self.addAddressView || touch.view == self.titleScrollView) {
        return NO;
    }
    return YES;
}


@end
